package com.project.controller.web;

import com.project.common.utils.Constants;
import com.project.common.utils.ExcelUtil;
import com.project.common.utils.Util;
import com.project.entity.*;
import com.project.myBeans.ConfigParameters;
import com.project.myBeans.R;
import com.project.myBeans.ResponseBean;
import com.project.service.*;
import com.project.service.base.BaseService;
import com.project.service.base.CrpData.CryFileUtil;
import com.project.service.base.CrpData.CrypDataHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: TateBrown
 * @date: 2018/5/27 18:03
 * @param:
 * @return:
 */
@EnableAutoConfiguration //自动载入应用程序所需的所有Bean
@RestController //@Controller与@ResponseBody的合并
@RequestMapping(value = "/upload")
@Api(description = "文件上传接口",value = "upload")
public class UploadController extends BaseService {
    @Autowired
    private CryFileUtil cryFileUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private StudentInfoService studentInfoService;

    @Autowired
    private TeacherInfoService teacherInfoService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private CvService cvService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private ClassService classService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private SchoolManagerInfoService schoolManagerInfoService;

    @Autowired
    private MagFacultyInfoService magFacultyInfoService;

    @Autowired
    private SysInfoService sysInfoService;

    @Autowired
    private ConfigParameters configParameters;

    @Autowired
    private UniversityService universityService;

    @Autowired
    private CrypDataHelper crypDataHelper;

    /**
     * TateBrown 2018年5月25日
     *
     * @param file
     * @param request
     * @return
     */
    @ApiOperation("上传公司单位外景图片")
    @PostMapping("/out")
    @Deprecated
    public R out(@RequestParam("fileUp") CommonsMultipartFile file, HttpServletRequest request) {
        try {
            String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/static/upload/out");
            //多级地创建目录
            File f1 = new File(savePath);
            if (!f1.exists()) f1.mkdirs();

//            上传文件在服务器的文件名
            String fileName = "";

            file.getFileItem().getName();

//            获取文件格式
            String name = file.getOriginalFilename();

            String ext = name.substring(name.lastIndexOf('.'));

//            保存到服务器后的新文件名
            fileName = System.currentTimeMillis() + ext;
//            创建文件保存对象
            File f = new File(savePath + "/" + fileName);
//            访问的绝对路径
            String fullPath = "/static/upload/out" + "/" + fileName;

//            获取文件输出流
            FileOutputStream out = new FileOutputStream(f);


//            保存文件
            FileCopyUtils.copy(file.getInputStream(), out);


//            file.getFileItem().write(f);

            System.out.println(fileName);


           return R.ok().put("data",fullPath);

        } catch (IOException e) {
            e.printStackTrace();
           return R.error();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }


    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param file
     * @param request
     * @return
     */
    @ApiOperation("加密上传公司营业执照")
    @PostMapping("/businessliscense")
    @Deprecated
    public R businessliscense(@RequestParam("fileUp") CommonsMultipartFile file, HttpServletRequest request) {
        try {
            String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/static/upload/businessliscense");
            //多级地创建目录
            File f1 = new File(savePath);
            if (!f1.exists()) f1.mkdirs();

//            上传文件在服务器的文件名
            String fileName = "";

            file.getFileItem().getName();

//            获取文件格式
            String name = file.getOriginalFilename();

            String ext = name.substring(name.lastIndexOf('.'));

//            保存到服务器后的新文件名
            fileName = new Date().getTime() + ext;


//            创建文件保存对象
            File f = new File(savePath + "/" + fileName);

            String fullPath = "/WEB-INF/static/upload/businessliscense" + "/" + fileName;
//            获取文件输出流
            FileOutputStream out = new FileOutputStream(f);

//             获得加密后的文件字节流
            byte[] data = cryFileUtil.encry(file.getBytes());

//            保存文件
            FileCopyUtils.copy(data, out);

//            保存文件
//            FileCopyUtils.copy(file.getInputStream(), out);

            System.out.println(fileName);

            return R.ok().put("data",fullPath);

        } catch (IOException e) {
            e.printStackTrace();
            return R.error();
        }

    }

    /**
     * TateBrown 2018年5月25日
     *
     * @param file
     * @param classId 班级id
     * @return
     */
    @ApiOperation("Excel批量导入学生信息")
    @PostMapping("/addStudentBatch/{classId}")
    public R importStudentBatch(@RequestParam("fileUp") CommonsMultipartFile file, @PathVariable("classId") Integer classId, HttpServletRequest request) {
        String name = System.currentTimeMillis() + "导入失败数据.xlsx";
        try {

            String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/static/temp");
            com.project.entity.Class clazz = classService.findOne(classId);


            //学校/学院/系/专业
            Integer universityId = clazz.getUniversityid();
            Integer schoolId = clazz.getSchoolid();
            Integer departmentId = clazz.getDepartmentid();
            Integer majorId = clazz.getMajorid();

            String defaultPassword = getDeafultPassword(departmentId);

            //多级地创建目录
            File f1 = new File(savePath);
            if (!f1.exists()) f1.mkdirs();
            File Response = new File(savePath + "/" + name);
            Response.createNewFile();
            Map<String, List<String>> map = ExcelUtil.parse(file.getInputStream());
            Map<String, List<String>> errorData = new HashMap<>();
            errorData.put("title", map.get("0"));
            //移除第一行 （标题）
            map.remove("0");

            for (Map.Entry<String, List<String>> e : map.entrySet()) {
                try {
                    List data = e.getValue();
                    if (data != null) {
                        User user = new User();
                        user.setUniversityid(universityId);
                        user.setSchoolid(schoolId);
                        user.setUsertype(Constants.USERTYPE.STUDENT.value());//账户类型设置为学生
                        user.setUsername((String) data.get(1));
                        user.setWorkid((String) data.get(1));
                        user.setRealname((String) data.get(2));
                        user.setMobilephone((String) data.get(3));
                        user.setPassword(defaultPassword);

                        StudentInfo studentInfo = new StudentInfo();
                        studentInfo.setUserid(user.getId());
                        studentInfo.setSchoolid(schoolId);
                        studentInfo.setMajorid(majorId);
                        studentInfo.setDepartmentid(departmentId);
                        studentInfo.setClassid(classId);
                        //studentInfoService.add(studentInfo);
                        studentService.addDetailOne(user, studentInfo);
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                    errorData.put(e.getKey(), e.getValue());
                }

            }
            if (errorData.size() == 1) {
               return R.ok();
            } else {
                //创建错误数据表
                ExcelUtil.importErrorData(Response, errorData);
                return R.error().put("data",name);
            }

        } catch (Exception e2) {
            e2.printStackTrace();
            return R.error();
        }
    }

    /**
     * author: WheelChen
     * date: 2017/11/30
     * function: 获取上传时设置的默认密码
     *
     * @param schoolId
     * @return
     */
    String getDeafultPassword(Integer schoolId) {
        School school = schoolService.findOne(schoolId);
        if (school != null)
            if (StringUtils.hasText(school.getUserdefaultpwd())) return school.getUserdefaultpwd();
        //若无则使用系统默认密码
        return sysInfoService.findOneByPropertyName("defaultpassword").getPropertyvalue();
    }

    /**
     * TateBrown 2018年5月25日
     *
     * @param file
     * @param request
     * @return
     */
    @ApiOperation("上传工作环境招聘")
    @PostMapping("/workingpic")
    @Deprecated
    public R workingpic(@RequestParam("fileUp") CommonsMultipartFile file, HttpServletRequest request) {
        try {
//            Integer classId = Integer.getInteger(request.getParameter("classid"));
//            System.out.println(classId);
            String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/static/upload/workingpic");
            //多级地创建目录
            File f1 = new File(savePath);
            if (!f1.exists()) f1.mkdirs();

//            上传文件在服务器的文件名
            String fileName = "";

//            获取文件格式
            String name = file.getOriginalFilename();

            String ext = name.substring(name.lastIndexOf('.'));

//            保存到服务器后的新文件名
            fileName = System.currentTimeMillis() + ext;
//            创建文件保存对象
            File f = new File(savePath + "/" + fileName);
//            访问的绝对路径
            String fullPath = "/static/upload/workingpic" + "/" + fileName;

//            获取文件输出流
            FileOutputStream out = new FileOutputStream(f);

//            保存文件
            FileCopyUtils.copy(file.getInputStream(), out);

            return R.ok().put("data",fullPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return R.error();
        } catch (IOException e) {
            e.printStackTrace();
            return R.error();
        }
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param file
     * @param session
     * @return
     */
    @ApiOperation("上传实习协议文件pdf")
    @PostMapping("/contract")
    public R contract(@RequestParam("fileUp") CommonsMultipartFile file,
                                 HttpSession session) {

        try {
            User user = (User) session.getAttribute("currentUser");

//            String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/static/upload/contract");
            String savePath;
            //绝对路径
            String rootPath = Util.getWebRootURL(this);

            //获取用户表/学生表/学院表信息
            StudentInfo studentInfo = studentInfoService.findOneByUserId(user.getId());
            com.project.entity.Class clazz = classService.findOne(studentInfo.getClassid());
            School school = schoolService.findOne(user.getSchoolid());
            University university = universityService.findOne(user.getUniversityid());

            //为每个学生根据/学校id/学院id/班级id/学号 建立文件夹
            String belong = user.getUniversityid() +
                    "/" + school.getId() +
                    "/" + studentInfo.getClassid() +
                    "/" + user.getWorkid() +
                    "/" + "internagreement";

            savePath = rootPath + "/" + belong;

            //多级地创建目录
            File f1 = new File(savePath);

            if (!f1.exists()) f1.mkdirs();

//            上传文件在服务器的文件名
            String fileName = "";

            file.getFileItem().getName();

//            获取文件格式
            String name = file.getOriginalFilename();

            String ext = name.substring(name.lastIndexOf('.'));

//            保存到服务器后的新文件名
            fileName = user.getWorkid() + "-" + crypDataHelper.decRealName(user.getRealname()) + "-" + new Date().getTime() + ext;

//            创建文件保存对象
            File f = new File(savePath + "/" + fileName);

            //            简历下分级目录
            String fullPath =
                    "/" + user.getUniversityid() +
                            "/" + school.getId() +
                            "/" + studentInfo.getClassid() +
                            "/" + user.getWorkid() +
                            "/" + "internagreement" +
                            "/" + fileName;

//            获取文件输出流
            FileOutputStream out = new FileOutputStream(f);

////             获得加密后的文件字节流
//            byte[] data = cryFileUtil.encry(file.getBytes());

//            保存文件
            FileCopyUtils.copy(file.getInputStream(), out);

            System.out.println(fileName);

           return R.ok().put("data",fullPath);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param file
     * @param request
     * @param session
     * @return
     */
    @ApiOperation("上传学生简历")
    @PostMapping("/addCv/{userId}")
    public R cv(@RequestParam("fileUp") CommonsMultipartFile file, @PathVariable("userId") Integer userId, HttpServletRequest request, HttpSession session) {

        try {

            //绝对路径
//            String absolutePath = request.getSession().getServletContext().getRealPath(basePath);
            String savePath;
            //绝对路径
            String rootPath = Util.getWebRootURL(this);

            //获取用户表/学生表/学院表信息
            User user = userService.findByUserIdUnDecry(userId);
            StudentInfo studentInfo = studentInfoService.findOneByUserId(userId);
            com.project.entity.Class clazz = classService.findOne(studentInfo.getClassid());
            School school = schoolService.findOne(user.getSchoolid());
            University university = universityService.findOne(school.getUniversityid());

            //为每个学生根据/学校id/学院id/班级id/学号 建立文件夹
            String belong = school.getUniversityid() +
                    "/" + school.getId() +
                    "/" + studentInfo.getClassid() +
                    "/" + user.getWorkid() + "/cv";

//            String belong = university.getName() +
//                    "/" + school.getName() +
//                    "/" + clazz.getName() +
//                    "/" + user.getWorkid() + "/cv";

            savePath = rootPath + "/" + belong;

            //多级地创建目录
            File f1 = new File(savePath);

            if (!f1.exists()) f1.mkdirs();

            //上传文件在服务器的文件名
            String fileName;

//            获取文件格式
            String name = file.getOriginalFilename();
            String ext = Util.getExt(name);

//            保存到服务器后的新文件名
            fileName = new Date().getTime() + "." + ext;

//            创建文件保存对象
            File f = new File(savePath + "/" + fileName);

//            简历下分级目录
            String fullPath =
                    "/" + school.getUniversityid() +
                            "/" + school.getId() +
                            "/" + studentInfo.getClassid() +
                            "/" + user.getWorkid() +
                            "/" + "cv" +
                            "/" + fileName;


//            获取文件输出流
            FileOutputStream out = new FileOutputStream(f);

//            保存文件
            FileCopyUtils.copy(file.getInputStream(), out);

            //保存简历记录
            Cv cv = new Cv();
            cv.setFilename(fullPath);
            cv.setStid(userId);
            cvService.addOne(cv);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param file
     * @param request
     * @param response
     * @return
     */
    @ApiOperation("学生自我介绍图片上传")
    @PostMapping("/ckeditor/intro")
    public void intro(@RequestParam("upload") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        User user = (User) session.getAttribute("currentUser");
        Integer userId = user.getId();

        String savePath = "";

        //设置返回头
        response.setContentType("text/html;charset=UTF-8");
        //绝对路径
        String rootPath = Util.getWebRootURL(this);


        //获取用户表/学生表/学院表信息
        StudentInfo studentInfo = studentInfoService.findOneByUserId(userId);

        //为每个学生根据/学校id/学院id/班级id/学号 建立文件夹
        String belong = user.getUniversityid() +
                "/" + studentInfo.getSchoolid() +
                "/" + studentInfo.getClassid() +
                "/" + user.getWorkid();

        savePath = rootPath + "/" + belong + "/intro";

        //多级地创建目录
        File f1 = new File(savePath);

        if (!f1.exists()) f1.mkdirs();

        //获取文件格式
        String name = file.getOriginalFilename();

        String ext = Util.getExt(name);

        //保存到服务器后的新文件名
        String fileName = new Date().getTime() + "." + ext;

        //创建文件保存对象
        File f = new File(savePath + "/" + fileName);

        //访问的绝对路径
        String fullPath =
                configParameters.getServer() +
                        "/" + belong +
                        "/" + "intro" +
                        "/" + fileName;

        try {
            //获取文件输出流
            FileOutputStream out1 = new FileOutputStream(f);
            //保存文件
            FileCopyUtils.copy(file.getInputStream(), out1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String CKEditorFuncNum = request.getParameter("CKEditorFuncNum");
        PrintWriter out;

        //回调返回给前端ckeditor
        String s = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", '" + fullPath + "');</script>";
        try {
            out = response.getWriter();
            out.print(s);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param file
     * @param request
     * @param response
     * @param session
     * @return
     */
    @ApiOperation("学生编写实习日志中的图片上传")
    @PostMapping("/ckeditor/diary")
    public void diary(@RequestParam("upload") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        User user = (User) session.getAttribute("currentUser");

        StudentInfo studentInfo = studentInfoService.findOneByUserId(user.getId());

        //设置返回头
        response.setContentType("text/html;charset=UTF-8");

        //获取项目upload文件夹真实地址
//        String savePath = request.getSession().getServletContext().getRealPath(baseURL);
        String savePath = "";
        //绝对路径
        String rootPath = Util.getWebRootURL(this);

        //为每个学生根据/学校id/学院id/班级id/学号 建立文件夹
        String belong = user.getUniversityid() +
                "/" + studentInfo.getSchoolid() +
                "/" + studentInfo.getClassid() +
                "/" + user.getWorkid();

        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateNowStr = sdf.format(d);

        savePath = rootPath + "/" + belong + "/diary" + "/" + dateNowStr;

        //多级地创建目录
        File f1 = new File(savePath);

        if (!f1.exists()) f1.mkdirs();

        //获取文件格式
        String ext = Util.getExt(file.getOriginalFilename());

        //保存到服务器后的新文件名
        String fileName = new Date().getTime() + "." + ext;

        //创建文件保存对象
        File f = new File(savePath + "/" + fileName);

        //访问的相对路径
        String fullPath = configParameters.getServer() + "/" + belong + "/" + "diary" + "/" + dateNowStr + "/" + fileName;

        try {
            //获取文件输出流
            FileOutputStream out1 = new FileOutputStream(f);
            //保存文件
            FileCopyUtils.copy(file.getInputStream(), out1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String CKEditorFuncNum = request.getParameter("CKEditorFuncNum");
        PrintWriter out;

        //回调返回给前端ckeditor
        String s = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", '" + fullPath + "');</script>";
        try {
            out = response.getWriter();
            out.print(s);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * TateBrown 2018年5月25日
     *
     * @param file
     * @param request
     * @param response
     * @param session
     * @return
     */
    @ApiOperation("学生编写实习日志中的图片上传")
    @PostMapping("/ckeditor/notice")
    public void notice(@RequestParam("upload") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        User user = (User) session.getAttribute("currentUser");

        System.out.println(user.getId());

        MagFacultyInfo magFacultyInfo = magFacultyInfoService.findByUserId(user.getId());

        //设置返回头
        response.setContentType("text/html;charset=UTF-8");

        //获取项目upload文件夹真实地址
//        String savePath = request.getSession().getServletContext().getRealPath(baseURL);
        String savePath = "";
        //绝对路径
        String rootPath = Util.getWebRootURL(this);

        String belong = String.valueOf(magFacultyInfo.getSchoolid());
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateNowStr = sdf.format(d);

        savePath += rootPath + "/" + belong + "/" + "notice" + "/" + dateNowStr;


        //多级地创建目录
        File f1 = new File(savePath);

        if (!f1.exists()) f1.mkdirs();

        //获取文件格式
        String ext = Util.getExt(file.getOriginalFilename());

        //保存到服务器后的新文件名
        String fileName = new Date().getTime() + "." + ext;


        //创建文件保存对象
        File f = new File(savePath + "/" + fileName);

        //访问的相对路径
        String fullPath = configParameters.getServer() + "/" + belong + "/" + "notice" + "/" + dateNowStr + "/" + fileName;

        try {
            //获取文件输出流
            FileOutputStream out1 = new FileOutputStream(f);
            //保存文件
            FileCopyUtils.copy(file.getInputStream(), out1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String CKEditorFuncNum = request.getParameter("CKEditorFuncNum");
        PrintWriter out;

        //回调返回给前端ckeditor
        String s = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", '" + fullPath + "');</script>";
        try {
            out = response.getWriter();
            out.print(s);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
